package com.gt.task;

import com.alibaba.fastjson.JSONObject;
import com.gt.entity.RestTemplateLog;
import com.gt.service.RestTemplateLogService;
import com.gt.utils.DatetimeUtil;
import com.gt.utils.LocalIp;
import com.gt.utils.ObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * restTemplate 存储日志
 */
@Service
public class RestTemplateSaveLog  implements RestTemplateTask {
    final static Logger log = LoggerFactory.getLogger(RestTemplateSaveLog.class);
    public final static String TRACE_ID = "trace_id";
    @Autowired
    private RestTemplateLogService restTemplateLogService;

    @Override
    @Async
    public void execute(HttpRequest request, ClientHttpResponse response, byte[] body, JSONObject args) {
        try {
            doExecute(request,response,body,args);
        }catch (Exception e){
            log.error("RestTemplate日志存储异常",e);
        }
    }

    private void doExecute(HttpRequest request, ClientHttpResponse response, byte[] body, JSONObject args) throws IOException {
        // ID、请求地址、请求方式、请求头、请求日志
        String uri = request.getURI().toString();//请求地址
        String method = request.getMethod().toString();//请求方式
        String head = request.getHeaders().toString();//请求头
        String requestBody = new String(body, "UTF-8");//请求日志

        // 耗时、响应状态码、响应状态码内容、响应头、响应日志、创建时间
        Long timeConsuming = args.getLong("timeConsuming");//耗时
        String status = response.getStatusCode().toString();//响应状态码
        String statusText = response.getStatusText();//响应状态码内容
        String headResp = response.getHeaders().toString();//响应头
        String responseBody = RestTemplatePrintLog.getResponseBody(response);//响应日志
        String nowSSS = DatetimeUtil.getNowSSS();//创建时间

        RestTemplateLog log = new RestTemplateLog();
        log.setUri(uri);
        log.setMethod(method);
        log.setHead(head);
        log.setRequestBody(requestBody);
        log.setTimeConsume(timeConsuming);
        log.setRespStatus(status);
        log.setRespStatusText(statusText);
        log.setRespHead(headResp);
        log.setRespBody(responseBody);
        log.setCreateTime(nowSSS);
        log.setMdcCode(MDC.get(TRACE_ID));// mdc编码
        log.setLocalIp(LocalIp.getServerIp()); // 本地IP地址
        // 属性长度截取，防止过长
        ObjectUtil.cuttingStrFields(log);
        restTemplateLogService.insert(log);
    }

}
